<template>
    <main>
        <h1>欢迎{{ title }}</h1>
        <form method="POST" @submit.prevent="isLogin ? login() : register()">
            <p class="title">
                <span>{{ title }}</span>
                <router-link :to="{ name: isLogin ? 'Register' : 'Login' }">{{ isLogin ? '立即注册' : '前往登录' }}</router-link>
            </p>
            <message-box :message="message"></message-box>
            <p>用户名称：<input type="text" name="username" v-model="username" placeholder="请输入用户名"></p>
            <p>用户密码：<input type="password" name="password" v-model="password" placeholder="请输入密码"></p>
            <template v-if="!isLogin">
                <p>确认密码：<input type="password" name="confirmPassword" v-model="confirmPassword" placeholder="确认密码"></p>
                <p>电子邮件：<input type="email" name="email" v-model="email" placeholder="请输入邮箱地址"></p>
                <p class="captcha">
                    验证码：<input type="text" name="captcha" v-model="captcha">
                    <img @click="changeCaptcha" title="点击切换验证码" :src="captchaUrl">
                </p>
            </template>
            <p><button class="btn-success w-100 mt-20px">{{ title }}</button></p>
        </form>
    </main>
</template>

<script>
    import MessageBox from '../../components/MessageBox.vue';
    import userService from '../../service/UserService';
    import { getValueFromCookie } from '../../utils';

    /** 验证码请求路径 */
    const CAPTCHA_DEFAULT_URL = '/kaptcha';

    /**
     * 登录、注册页面
     */
    export default {
        components: {
            MessageBox
        },
        data() {
            return {
                message: '',            // 提示信息
                captchaUrl: CAPTCHA_DEFAULT_URL,    // 验证码请求URL
                username: '',           // 用户名
                password: '',           // 密码
                confirmPassword: '',    // 确认密码
                email: '',              // 邮箱
                captcha: ''             // 验证码
            }
        },
        computed: {
            /**
             * 页面标题
             */
            title() {
                return this.$route.meta.title;
            },
            /**
             * 是否是登录页面
             */
            isLogin() {
                return this.$route.name === 'Login';
            }
        },
        methods: {
            /**
             * 登录
             */
            async login() {
                const result = await userService.login({
                    username: this.username,
                    password: this.password,
                });
                if (result.isFail) {
                    // 登录失败
                    this.message = result.message;
                    return;
                }
                // 登录成功，将用户数据保存到Vuex中，然后跳转到首页
                this.$store.commit('loginUser/login', result.data);
                this.$router.push({ name: 'Home' });
            },
            /**
             * 注册
             */
            async register() {
                const result = await userService.register({
                    username: this.username,
                    password: this.password,
                    confirmPassword: this.confirmPassword,
                    email: this.email,
                    captcha: this.captcha
                });
                if (result.isFail) {
                    // 注册失败，显示提示信息，清空密码和验证码，切换验证码
                    this.message = result.message;
                    this.password = this.confirmPassword = this.captcha = '';
                    this.changeCaptcha();
                    return;
                }
                // 注册成功，将用户数据保存到Vuex中，然后跳转到首页
                this.$store.commit('loginUser/login', result.data);
                this.$router.push({ name: 'Home' });
            },
            /**
             * 验证码图片点击切换功能（点击事件）
             */
            changeCaptcha() {
                this.captchaUrl = `${ CAPTCHA_DEFAULT_URL }#${ Date.now() }`;
            }
        },
        created() {
            if (this.isLogin) {
                this.username = getValueFromCookie('username');
            }
        },
        mounted() {
            if (!this.isLogin) {
                // 验证码图片点击切换功能
                this.changeCaptcha();
            }
        }
    }
</script>

<style lang="less" scoped>
    main {
        width: 100vw;
        display: flex;
        justify-content: space-around;
        align-items: center;
        background-color: var(--color-success);
        border: none;
        h1 {
            color: #fff;
            margin-bottom: 100px;
            font-weight: 500;
            font-size: 40px;
        }
        :deep(form) {
            width: 400px;
        }
    }
</style>